package com.kime.email.book;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;

/**
 * Java 邮件开发详解
 * 邮件发送程序
 */
public class HtmlMessageSender {

    String protocol = "smtp";
    String from = "kimewen@163.com";
    String to = "kimewen@qq.com";
    String subject = "HTML 测试";
    String body = "<h4>欢迎大家阅读此邮件</h4>" +
            "<a href='https://www.baidu.com'>访问百度</a></br>" +
            "<img src=\"https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png\"><br/>" +
            "<p>这是一张图片</p>" +
            "<img src=\"cid:logo_oppo\"";

    public static void main(String[] args) throws Exception{
        String server = "smtp.163.com";
        String user = "kimewen@163.com";
        String password = "OTWWWGKLGSAFQPNE";

        HtmlMessageSender sender = new HtmlMessageSender();
        Session session = sender.createSession();
        MimeMessage message = sender.createMessage(session);

        // 获得 Transport 对象，并连接邮件服务器
        Transport transport = session.getTransport();
        transport.connect(server, user, password);
        transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
        transport.close();

    }

    private Session createSession() {
        Properties properties = new Properties();
        properties.setProperty("mail.transport.protocol", protocol);
        properties.setProperty("mail.smtp.auth", "true");
        Session session = Session.getInstance(properties);
        session.setDebug(true);
        return session;
    }

    private MimeMessage createMessage(Session session) throws Exception {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        message.setSubject(subject);
        MimeMultipart mimeMultipart = new MimeMultipart("related");
        MimeBodyPart htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setContent(body, "text/html;charset=gb2312");
        mimeMultipart.addBodyPart(htmlBodyPart);

        MimeBodyPart pictureBodyPart = new MimeBodyPart();
        FileDataSource fileDataSource = new FileDataSource("D:\\workspace\\email-demo\\src\\main\\resources\\image\\oppo.png");
        pictureBodyPart.setDataHandler(new DataHandler(fileDataSource));
        pictureBodyPart.setFileName(fileDataSource.getName());
        pictureBodyPart.setContentID("logo_oppo");
        mimeMultipart.addBodyPart(pictureBodyPart);

        message.setContent(mimeMultipart);
        message.saveChanges();
        return message;
    }
}
